<template>
  <div class="upload-img-container">
    <el-upload
      class="avatar-uploader"
      :http-request="handleUploadSubmit"
      ref="uploadRef"
      action="/api/upload"
      :show-file-list="false"
    >
      <img v-if="value" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadImgAPI } from "@/api/uploadimg";
import { setDevImg } from "@/utils";
export default {
  name: "UploadImg",
  props: ["value"],
  methods: {
    async handleUploadSubmit(file) {
      const res = await uploadImgAPI(file.file);
      if (typeof res !== "string") {
        this.$message.success("图片上传成功");
        this.$emit("input", setDevImg(res.data));
        this.$emit("onload", res.data);
      } else {
        const { msg } = JSON.parse(res);
        this.$message.error(msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}
.upload-img-container:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar,
.upload-img-container {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;
  display: block;
}
</style>
